package com.dengdai.applibrary.json;

import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @说明 数据解析
 * @作者 LY
 * @时间 16/5/9 16:19
 * @邮箱 2743569843@qq.com
 * @版权 Copyright(c) 2016 LY-版权所有
 * @备注
 */
public class Jackson {

    /**
     * JSON数据解析成对象
     *
     * @param dataJson
     * @param c
     * @param <T>
     * @return
     */
    public static <T> T parseClass(String dataJson, Class<T> c) {
        T t = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.getDeserializationConfig().set(org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            t = objectMapper.readValue(dataJson, c);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }

    /**
     * JSONArray数据解析成对象数组
     *
     * @param array
     * @param c
     * @param <T>
     * @return
     */
    public static <T> List<T> getList(String array, Class<T> c) {
        List<T> list = new ArrayList<T>();
        try {
            JSONArray jsonArray = new JSONArray(array);
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.getDeserializationConfig().set(org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            for (int i = 0; i < jsonArray.length(); i++) {
                T t = objectMapper.readValue(jsonArray.getString(i), c);
                list.add(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 对象转换成JSONObject
     *
     * @param o
     * @return
     */
    public static JSONObject getJSONObject(Object o) {
        JSONObject jsonObj = null;
        try {
            StringWriter sw = new StringWriter();
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.writeValue(sw, o);
            jsonObj = new JSONObject(sw.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObj;
    }
}
